import * as vscode from 'vscode';
import {CancellationToken} from "vscode";
import {authorizationVerification, getCompletion} from "../authorize";
import {getAllCompletionItems} from "./index";

export function createLuaHoverCompletionProvider(context: vscode.ExtensionContext) {

    context.subscriptions.push(vscode.languages.registerHoverProvider('lua',{
        async provideHover(document: vscode.TextDocument, position: vscode.Position, cancellationToken: CancellationToken) {
                if (getCompletion(context) === 'false'){
                    return;
                }

                const isAuthorized = await authorizationVerification(context);
                if (!isAuthorized) {
                    return undefined;
                }

                const range = document.getWordRangeAtPosition(position);
                const word = document.getText(range);
                let allItems = getAllCompletionItems();
                // 查找字符串对应的文档
                let item = allItems.find(i => i.label === word);
                let hoverMessage: vscode.MarkdownString | undefined;

                if (item && item.documentation) {
                    if (typeof item.documentation === 'string') {
                        hoverMessage = new vscode.MarkdownString(item.documentation);
                    } else {
                        hoverMessage = item.documentation;
                    }
                } else {
                    hoverMessage = new vscode.MarkdownString(`未找到 ${word} 的文档。`);
                }
                return new vscode.Hover(hoverMessage);
            }
    }));
}
